<template>
  <div v-show="!loading">
    <div class="article-box" v-if="articleInfo">
      <div class="title">{{articleInfo.title}}</div>
      <div class="info-box">
        <div class="left">
          <img :src="articleInfo.avatar">
        </div>
        <div class="middle">
          <span>{{articleInfo.author}}</span>
          <div>
            <span>{{dateFormat(articleInfo.createTime,'yyyy/MM/dd')}}</span>
            <span>·</span>
            <span>点赞 {{articleInfo.praise}}</span>
          </div>
        </div>
        <div class="right" :class="{followed: followedFlag}" @click="follow(articleInfo.userId)">{{followedFlag? '已关注': '关注'}}</div>
      </div>
      <div class="short-content">
        <span class="red">摘要：</span>
        <span>{{articleInfo.summary}}</span>
      </div>
      <div class="cover">
        <img v-if="articleInfo.imgUrl" :src="articleInfo.imgUrl">
      </div>
      <div class="detail" v-html="articleInfo.details"></div>
      <div class="up-rewoard-box">
        <div>
          <div class="img-box" v-if="articleInfo.isPraise">
            <img src="../assets/uped.png">
          </div>
          <div class="img-box" v-else @click="up()">
            <img src="../assets/up.png">
          </div>
          <div>赞</div>
        </div>
        <!-- <div>
          <div class="img-box" @click="ctrlRewardAmountBox(true)">
            <img src="../assets/reward.png">
          </div>
          <div>打赏</div>
        </div> -->
      </div>
      <div class="reward-list-box">
        <template v-if="rewardList.length > 0">
          <div class="reward-avatar-box">
            <div :style="{ width: rewardList.length * 30 + 'rem' }">
              <template v-for="(item, index) in rewardList">
                <img v-if="index < 3" :style="{ left: index * 20 + 'rem' }" :key="index" :src="item.avatar" />
              </template>
            </div>
          </div>
          <span>{{rewardList.length > 3? '等': ''}}</span>
          <span class="num">{{rewardList.length}}</span>
          <span>人已打赏</span>
        </template>
        <template v-else>
          <span>首席赞赏官虚位以待</span>
        </template>
      </div>
      <div class="reward-amount-box" v-show="rewardAmountBoxFlag">
        <div class="main">
          <div class="reward-title">
            <span>打赏</span>
            <span class="close-btn" @click="ctrlRewardAmountBox(false)">×</span>
          </div>
          <div class="amount-box">
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
                <span v-if="index < 3" :key="item" :class="{'on': amountSelected === item}" @click="selectAmount(item)">￥{{item}}</span>
              </template>
            </div>
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
                <span v-if="index > 2" :key="item" :class="{'on': amountSelected === item}" @click="selectAmount(item)">￥{{item}}</span>
              </template>
            </div>
          </div>
          <div class="custom-amount">
            <input type="number" class="input-box" placeholder="自定义金额" v-model="inputAmount" @focus="inputFocus()">
            <div :class="{'disabled':amountSelected < 0 && inputAmount === ''}" @click="doReward()">打赏</div>
          </div>
        </div>
      </div>
      <div class="tips">
        文章内容仅供参考，不构成投资建议，投资有风险，入市需谨慎！
      </div>
      <div class="keyword-box">
        <template v-if="articleInfo.keyword">
          <span v-for="item in articleInfo.keyword.split(',')" :key="item">{{item}}</span>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from '@/utils/api'
import { dateFormat } from '@/utils/date'
import cookie from '@/utils/cookie'
import { operationType } from '@/utils/assist'
import { Toast, Indicator } from 'mint-ui'
import { setToken } from '@/utils/auth'
export default {
  name: 'index',
  components: {},
  data () {
    return {
      loading: true,
      followedFlag: true,
      articleInfo: {},
      rewardList: [
        // { avatar: 'https://dummyimage.com/30x30/fff&text=M' },
        // { avatar: 'https://dummyimage.com/30x30/000&text=B' },
        // { avatar: 'https://dummyimage.com/30x30/E13C31&text=L' },
        // { avatar: 'https://dummyimage.com/30x30/fff&text=M' },
        // { avatar: 'https://dummyimage.com/30x30/ccc&text=C' }
      ],
      rewardAmountBoxFlag: false,
      amountArr: [10, 20, 50, 66, 88, 100],
      inputAmount: '',
      amountSelected: 10,
      deviceType: null
    }
  },
  watch: {
    '$route' (to, val) {
      this.id = this.$route.params.id
      this.getData()
      return val
    }
  },
  created () {
    this.id = this.$route.params.id
    document.title = '文章详情'
    this.getTokenFromApp()
    this.initRewardedFn()
  },
  methods: {
    dateFormat: dateFormat,
    ctrlRewardAmountBox (flag) {
      this.rewardAmountBoxFlag = flag
    },
    selectAmount (item) {
      this.amountSelected = item
    },
    inputFocus () {
      this.amountSelected = -1
    },
    doReward () {
      let amount = 0
      if (this.amountSelected > -1) {
        amount = this.amountSelected
      } else {
        amount = this.inputAmount
      }
      let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (!reg.test(amount)) {
        Toast('请输入正确的金额')
        return
      }
      let rewardInfo = {
        payType: 'alipay',
        payAmount: amount,
        businessId: 1
      }
      let str = JSON.stringify(rewardInfo)
      alert(str)
      if (this.deviceType.android) {
        if (typeof window.androidApp !== 'undefined') {
          switch (rewardInfo.payType) {
            case 'alipay':
              Toast('向android app发送支付支付宝支付信息：' + str)
              window.androidApp.aliPay(str)
              break
            case 'wx':
              Toast('向android app发送微信支付信息：' + str)
              window.androidApp.wxPay(str)
              break
            default:
              break
          }
        }
      } else {
        if (typeof window.iosApp !== 'undefined') {
          switch (rewardInfo.payType) {
            case 'alipay':
              Toast('向ios app发送支付支付宝支付信息：' + str)
              window.iosApp.aliPay(str)
              break
            case 'wx':
              Toast('向ios app发送微信支付信息：' + str)
              window.iosApp.wxPay(str)
              break
            default:
              break
          }
        }
      }
    },
    async up () {
      let res = await api.praiseForArticle({
        articleId: this.id
      })
      if (res && res.code === 200) {
        this.articleInfo.isPraise = 1
      }
    },
    async follow (userId) {
      let params = {
        focusUserId: userId,
        focusStatus: this.followedFlag ? 1 : 0 // 1表示取消关注
      }
      let res = await api.focusUser(params)
      if (res.data) {
        let arr = ['关注失败']
        if (res.data.message) {
          arr.push(res.data.message)
        }
        Toast(arr.join(','))
      } else {
        if (this.followedFlag) {
          Toast('取消成功')
        } else {
          Toast('关注成功')
        }
        this.followedFlag = !this.followedFlag
      }
    },
    async getData () {
      try {
        Indicator.open()
        this.loading = true
        const id = this.$route.params.id
        let res = await api.getArticleDetail({ articleId: id }) // 计划文章
        Indicator.false()
        this.loading = false
        if (res) {
          this.articleInfo = res
        }
      } catch (error) {
        Toast('数据加载失败')
      }
    },
    // 调用app的方法获取token
    getTokenFromApp () {
      this.deviceType = operationType()
      let token = null
      if (this.deviceType.mobile) {
        if (this.deviceType.android) {
          if (typeof window.androidApp !== 'undefined') {
            token = window.androidApp.getToken()
            cookie.set('device_id', token)
            sessionStorage.setItem('token', token)
            this.getData()
          }
        } else {
          setTimeout(() => {
            if (typeof window.iosApp !== 'undefined') {
              token = window.iosApp.getToken()
            }
          }, 500)
        }
      } else {
        token = 'NzFEODU5RDJDOTJFN0M5OUU0QjZFNzI4OTE2MjlGREY3Qzg5MzIxRTAzMTYxNUE4MUNDMkM0MTM1M0RFNjgyNUI3Q0FDQjIwMzg4NDRCMjc4QzRFRkZBQzFDMUY4REQ3Qjg0QUVDMEU2NDYzOUVGMzY0NkZBMEZFMTQxNTQ3NzkwNThCMUNCRjZGNEYwMzM0OEM0RTBBNDYyQzc4ODhBRTY0OTQ1Nzk0QzI1MkM0MDNENzcwNzYxNUNFRDc3QzY0NjhGQzU3NkFFOEY4NTczRjZFQTAzNTA4QUI1RjIxODRGNzgzQUQwQTE0ODA1OUJFNjg0NTk5MTlDQThCMUIyNzgzRENCQzRBMDYyQTI0NUNCMzdFRDRCQjI2ODEyQUQx'
        setToken(token)
        this.getData()
      }
    },
    initRewardedFn () {
      window.rewardSuccess = () => {
        alert('支付成功')
      }
      window.rewardFail = (res) => {
        alert('支付失败' + res)
      }
      window.receiveTokenFromIOS = (token) => {
        cookie.set('device_id', token)
        sessionStorage.setItem('token', token)
        this.getData()
      }
    }
  }
}
</script>
<style lang="scss" scope>
@import "../style/art-detail";
</style>
